﻿using Aliyun.OSS;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Cyss.Core.Helper
{
    /// <summary>
    /// 阿里云帮助类
    /// </summary>
    public static class AliyunHelper
    {

        /// <summary>
        /// 上传图片到阿里云
        /// </summary>
        /// <param name="IsName">是否重新命名</param>
        /// <returns></returns>
        public static string SaveFileToAliyun(string endpoint, string accessKeyId, string accessKeySecret, string bucketName, BaseFileModel file, bool IsName = false)
        {
            try
            {
                string FileName = file.FileName;
                if (IsName)
                {
                    FileName = $"{DateTime.Now.ToString("yyyyMMddHHmmssfff")}{Path.GetExtension(file.FileName)}";
                }

                // 上传文件到国内OSS。
                var clientSZ = new OssClient(endpoint, accessKeyId, accessKeySecret);
                var szClient = clientSZ.PutObject(bucketName, FileName, file.GetStream());

                if (szClient.HttpStatusCode == HttpStatusCode.OK)
                {
                    return FileName;
                }
            }
            catch (Exception ex)
            {
            }
            return "";
        }


        /// <summary>
        /// 删除阿里云图片
        /// </summary>
        /// <param name="bucketName">文件夹</param>
        /// <param name="objectName">文件名</param>
        /// <returns></returns>
        public static string DeleteFileToAliyun(string endpoint, string accessKeyId, string accessKeySecret, string bucketName, string objectName)
        {
            try
            {
                var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
                // 删除文件
                client.DeleteObject(bucketName, objectName);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return "";
        }
    }

    
}
